import 'package:myapp/src/utils/app_baidu_map_utils.dart';
import 'package:flutter/material.dart';
import 'dart:async';

class LocationInfo {
  final String address;
  final String? province;
  final String? city;
  final String? district;
  final double? latitude;
  final double? longitude;

  LocationInfo({
    required this.address,
    this.province,
    this.city,
    this.district,
    this.latitude,
    this.longitude,
  });
}

class LocationService {
  static Future<LocationInfo?> getCurrentLocation(BuildContext context) async {
    try {
      final completer = Completer<LocationInfo?>();
      
      await AppBaiduMapUtils.startLocation(context, (location) {
        if (location != null) {
          print('获取到位置信息: 地址=${location.address}, 纬度=${location.latitude}, 经度=${location.longitude}');
          print("街道：${location.street}");
          // 获取到位置信息: 地址=中国浙江省宁波市江北区庄桥街道海川路88号, 纬
          // 街道：海川路
          // 转换后的位置信息: 纬度=29.934062, 经度=121.53643
          if (location.latitude != null && location.longitude != null &&
              location.latitude! > 0 && location.longitude! > 0) {
            final result = LocationInfo(
              address: location.address ?? '',
              province: location.province,
              city: location.city,
              district: location.district,
              latitude: location.latitude,
              longitude: location.longitude,
            );
            print('转换后的位置信息: 纬度=${result.latitude}, 经度=${result.longitude}');
            completer.complete(result);
          } else {
            print('获取到的经纬度无效: 纬度=${location.latitude}, 经度=${location.longitude}');
            completer.complete(null);
          }
        } else {
          completer.complete(null);
        }
      });

      return await completer.future;
    } catch (e) {
      print('获取位置失败: $e');
      return null;
    } finally {
      AppBaiduMapUtils.stopLocation(context);
    }
  }
} 